<template>
  <div class="contract-container">
    <h1>我的合同</h1>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-state">
      加载失败: {{ error.message }}
    </div>

    <!-- 空状态 -->
    <div v-else-if="!contracts || contracts.length === 0" class="empty-state">
      暂无合同
    </div>

    <!-- 合同列表 -->
    <div v-else class="contract-list">
      <div
        v-for="contract in contracts"
        :key="contract.order_id"
        class="contract-item"
      >
        <div class="contract-details">
          <h2>{{ contract.order_product.name }}</h2>
          <p class="contract-status" :class="getStatusClass(contract.order_status)">
            {{ contract.order_status }}
          </p>
          <p class="order-number">订单号: {{ contract.order_id }}</p>
          <p class="purchase-time">{{ formatDate(contract.order_time) }}</p>

          <div class="contract-actions">
            <button
              v-if="contract.order_status !== '未审核'"
              @click="showContractDetail(contract.order_id)"
              class="detail-button"
            >
              查看详情
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 合同详情弹窗 -->
  <div v-if="showDetailModal" class="modal-overlay">
    <div class="modal-content">
      <div class="modal-header">
        <h3>合同详情</h3>
        <button @click="closeModal" class="close-button">&times;</button>
      </div>

      <div class="modal-body">
        <!-- 新增：合同内容展示区域 -->
        <div class="contract-content-section">
          <h4>合同内容</h4>
          <div class="contract-text" v-if="contractText">
            {{ contractText }}
          </div>
          <div v-else class="contract-empty-state">
            <p>正在加载合同内容...</p>
          </div>
        </div>

        <!-- 语音消息区域 -->
        <div class="voice-section">
          <h4>语音消息中心</h4>
          <button
            @click="fetchVoiceData"
            :disabled="voiceLoading"
            class="fetch-voice-button"
          >
            {{ voiceLoading ? '加载中...' : '获取语音消息' }}
          </button>

          <!-- 语音列表 -->
          <div v-if="voiceItems.length > 0" class="voice-list-container">
            <h5>语音消息 ({{ voiceItems.length }})</h5>
            <div class="voice-list">
              <div
                v-for="(item, index) in voiceItems"
                :key="index"
                class="voice-item"
                :class="{ 'active': currentPlaying === index }"
              >
                <div class="voice-content">
                  <p class="voice-text">{{ item.text }}</p>
                  <div class="voice-controls">
                    <button
                      @click="togglePlay(index)"
                      class="play-button"
                      :disabled="voiceLoading"
                    >
                      <span v-if="currentPlaying !== index">▶ 播放</span>
                      <span v-else>⏸ 暂停</span>
                    </button>
                    <div class="voice-progress">
                      <div
                        class="progress-bar"
                        :style="{ width: currentProgress[index] + '%' }"
                      ></div>
                    </div>
                    <span class="duration">{{ formatDuration(item.duration) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 语音空状态 -->
          <div v-else-if="!voiceLoading" class="voice-empty-state">
            <p>暂无语音消息，请点击按钮获取</p>
          </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 音频元素 -->
    <audio
      ref="audioPlayer"
      @timeupdate="updateProgress"
      @ended="onAudioEnd"
      hidden
    ></audio>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

// 合同列表相关
const contracts = ref([]);
const loading = ref(true);
const error = ref(null);

// 弹窗相关
const showDetailModal = ref(false);
const currentContractId = ref(null);

// 语音消息相关
const voiceItems = ref([]);
const currentPlaying = ref(null);
const audioPlayer = ref(null);
const currentProgress = ref({});
const voiceLoading = ref(false);

// 获取合同数据
const fetchContracts = async () => {
  try {
    loading.value = true;
    const response = await axios.get('http://127.0.0.1:8000/ai/getshop', {
      params: { user_id: localStorage.getItem('user_id') }
    });

    // 确保数据是数组格式
    contracts.value = Array.isArray(response.data.data)
      ? response.data.data
      : [response.data.data];

  } catch (err) {
    console.error('获取合同失败:', err);
    error.value = err;
  } finally {
    loading.value = false;
  }
};

const contractText = ref('');

// 显示合同详情弹窗
const showContractDetail = async (contractId) => {
  currentContractId.value = contractId;
  showDetailModal.value = true;
  voiceItems.value = [];

  // 新增：获取合同文本
  try {
    const response = await axios.get('http://127.0.0.1:8000/ai/gethetong/', {
      params: { shopid: contractId }
    });
    contractText.value = response.data.data;
  } catch (error) {
    console.error('获取合同内容失败:', error);
    contractText.value = '获取合同内容失败';
  }
};

// 关闭弹窗
const closeModal = () => {
  showDetailModal.value = false;
  // 停止正在播放的音频
  if (currentPlaying.value !== null) {
    audioPlayer.value.pause();
    currentPlaying.value = null;
  }
};

// 获取语音数据
const fetchVoiceData = async () => {
  try {
    voiceLoading.value = true;
    voiceItems.value = []; // 清空现有数据

    const response = await axios.post('http://127.0.0.1:8000/ai/listion/', {
      shopid: currentContractId.value
    }, {
      responseType: 'blob'
    });

    // 创建一个新的语音项
    const newItem = {
      id: Date.now(),
      audioBlob: response.data,
      text: '合同审核结果语音',
      duration: 0
    };

    voiceItems.value.push(newItem);
    currentProgress.value[voiceItems.value.length - 1] = 0;

    // 获取音频时长
    await updateAudioDuration(voiceItems.value.length - 1);

  } catch (error) {
    console.error('获取语音数据失败:', error);
    alert('获取语音数据失败');
  } finally {
    voiceLoading.value = false;
  }
};

// 更新音频时长
const updateAudioDuration = async (index) => {
  return new Promise((resolve) => {
    const audio = new Audio();
    audio.src = URL.createObjectURL(voiceItems.value[index].audioBlob);
    audio.onloadedmetadata = () => {
      voiceItems.value[index].duration = audio.duration;
      resolve();
    };
  });
};

// 切换播放状态
const togglePlay = (index) => {
  if (currentPlaying.value === index) {
    // 暂停当前播放
    audioPlayer.value.pause();
    currentPlaying.value = null;
  } else {
    // 播放新项目
    if (currentPlaying.value !== null) {
      audioPlayer.value.pause();
    }

    const audioUrl = URL.createObjectURL(voiceItems.value[index].audioBlob);
    audioPlayer.value.src = audioUrl;
    audioPlayer.value.play();
    currentPlaying.value = index;
  }
};

// 音频进度更新
const updateProgress = () => {
  if (currentPlaying.value !== null && audioPlayer.value) {
    const index = currentPlaying.value;
    const progress = (audioPlayer.value.currentTime / voiceItems.value[index].duration) * 100;
    currentProgress.value[index] = progress > 100 ? 100 : progress;
  }
};

// 音频结束
const onAudioEnd = () => {
  if (currentPlaying.value !== null) {
    currentProgress.value[currentPlaying.value] = 100;
    currentPlaying.value = null;
  }
};

// 格式化时长显示
const formatDuration = (seconds) => {
  if (!seconds) return '0:00';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
};

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString();
};

// 根据状态获取CSS类
const getStatusClass = (status) => {
  if (status.includes('未支付')) return 'status-unpaid';
  if (status.includes('未审核')) return 'status-unreviewed';
  return 'status-default';
};

onMounted(() => {
  fetchContracts();
});
</script>

<style scoped>

.contract-content-section {
  margin-bottom: 25px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.contract-content-section h4 {
  margin-top: 0;
  color: #2c3e50;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.contract-text {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #333;
  padding: 10px;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #eee;
}

.contract-empty-state {
  text-align: center;
  padding: 20px;
  color: #666;
  background-color: #f8f9fa;
  border-radius: 8px;
}

/* 调整语音部分的上边距 */
.voice-section {
  margin-top: 20px;
}

.contract-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

.loading-overlay {
  text-align: center;
  padding: 40px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #4a90e2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-state {
  text-align: center;
  padding: 40px;
  color: #f56c6c;
  font-size: 18px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  font-size: 18px;
  color: #666;
}

.contract-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.contract-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  transition: all 0.3s;
}

.contract-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.contract-details {
  padding: 15px;
}

.contract-details h2 {
  margin: 0 0 10px;
  font-size: 18px;
  color: #333;
}

.contract-status {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-bottom: 10px;
}

.status-unpaid {
  background-color: #fff6e6;
  color: #e6a23c;
}

.status-unreviewed {
  background-color: #fef0f0;
  color: #f56c6c;
}

.status-default {
  background-color: #f0f9eb;
  color: #67c23a;
}

.order-number, .purchase-time {
  font-size: 12px;
  color: #909399;
  margin: 5px 0;
}

.contract-actions {
  margin-top: 15px;
}

.detail-button {
  padding: 8px 16px;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.detail-button:hover {
  background-color: #3a7bc8;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0 10px;
}

.close-button:hover {
  color: #666;
}

.modal-body {
  padding: 20px;
}

/* 语音消息样式 */
.voice-section {
  margin-top: 20px;
}

.fetch-voice-button {
  padding: 8px 16px;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-bottom: 15px;
}

.fetch-voice-button:hover {
  background-color: #3a7bc8;
}

.fetch-voice-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.voice-list-container {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-top: 15px;
}

.voice-list-container h5 {
  margin-top: 0;
  color: #2c3e50;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.voice-list {
  margin-top: 10px;
}

.voice-item {
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  background-color: white;
}

.voice-item.active {
  background-color: #e7f2ff;
  border-left: 4px solid #4a90e2;
}

.voice-text {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.voice-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.play-button {
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  cursor: pointer;
  transition: background-color 0.2s;
  min-width: 80px;
}

.play-button:hover {
  background-color: #3a7bc8;
}

.play-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.voice-progress {
  flex-grow: 1;
  height: 6px;
  background-color: #e0e0e0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background-color: #4a90e2;
  transition: width 0.1s linear;
}

.duration {
  font-size: 14px;
  color: #666;
  min-width: 40px;
  text-align: right;
}

.voice-empty-state {
  text-align: center;
  padding: 20px;
  color: #666;
  background-color: #f8f9fa;
  border-radius: 8px;
}
</style>